package cn.shenshen.shop.service.impl;

import cn.shenshen.shop.domain.Good;
import cn.shenshen.shop.domain.SeckillGood;
import cn.shenshen.shop.fegin.GoodFeignApi;
import cn.shenshen.shop.mapper.SeckillMapper;
import cn.shenshen.shop.service.ISeckillGoodService;
import cn.shenshen.shop.util.BusinessException;
import cn.shenshen.shop.util.SeckillGoodCodeMsg;
import cn.shenshen.shop.util.Result;
import cn.shenshen.shop.vo.GoodVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SeckillGoodServiceImpl implements ISeckillGoodService{

    @Autowired
    private SeckillMapper seckillMapper;

    @Autowired
    private GoodFeignApi goodFeignApi;

    public List<GoodVo> query() {

        //查询出所有的秒杀商品
        List<SeckillGood> seckillGoods = seckillMapper.query();
        return getGoodVos(seckillGoods);

    }

    /**
     * 抽取的获取vo对象的方法
     * @param seckillGoods
     * @return
     */
    private List<GoodVo> getGoodVos(List<SeckillGood> seckillGoods) {
        //所有符合条件的商品id的组合
        Map<Long,SeckillGood> map = new HashMap<>();
        List<Long> goodIds = new ArrayList<>();
        for (SeckillGood seckillGood : seckillGoods) {
            map.put(seckillGood.getGoodId(),seckillGood);
            goodIds.add(seckillGood.getGoodId());
        }
        //发起fegin远程调用
        Result<List<Good>> goods = goodFeignApi.queryByIds(goodIds);
        //异常情况   goods为空
        //异常情况  code != 200
        if (goods == null || goods.hashError()){
            //异常处理
            throw new BusinessException(SeckillGoodCodeMsg.FEIGN_ERROR);
        }

        //组合vo对象
        List<GoodVo> goodVos = new ArrayList<>();
        //遍历商品列表
        for (Good good : goods.getData()) {
            //获取秒杀商品
            SeckillGood seckillGood = map.get(good.getId());
            GoodVo goodVo = new GoodVo();
            BeanUtils.copyProperties(good,goodVo);
            BeanUtils.copyProperties(seckillGood,goodVo);
            goodVos.add(goodVo);
        }
        return goodVos;
    }


    public GoodVo find(Long goodId) {
        //查询指定秒杀商品
        SeckillGood seckillGood  = seckillMapper.find(goodId);
        ArrayList<SeckillGood> seckillGoods = new ArrayList<>();
        if (seckillGood == null){
            throw new BusinessException(SeckillGoodCodeMsg.QUERY_SECKILLGOOD_ERROR);
        }
        seckillGoods.add(seckillGood);
        List<GoodVo> goodVos = getGoodVos(seckillGoods);
        return goodVos.get(0);
    }

    public int descStock(Long goodId) {
        return seckillMapper.descStock(goodId);
    }
}
